package com.yc.interceptor;

import com.yc.util.JwtTokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @author zwei
 * @create 2024-09-05 20:37
 */
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        if (token!=null&&   !jwtTokenUtil.isTokenExpired(token)){   //token不为空  并且没有过期
            //验证token是否过期
            try {
                //取出token中的负载部分
                Map<String,Object>claims=jwtTokenUtil.decodeJWTWithkey(token);
                //将负载部分放入request中 供后续controller使用
                request.setAttribute("userClaims",claims);
                return true;
            }catch (Exception e){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }
}
